package com.synergy.stockflow.utils;

import io.jsonwebtoken.Jwts;
import org.springframework.boot.SpringApplication;

import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class JwtSecretInitializer {

    private static final String CONFIG_PATH = "config/local-config.properties";
    private static final String JWT_SECRET_KEY = "stockflow.jwt.secret";

    public static SpringApplication init(SpringApplication application) throws IOException {
        // 创建 config 目录（如果不存在）
        Path path = Paths.get(CONFIG_PATH);
        if (!Files.exists(path)) {
            Files.createDirectories(path.getParent());
            Files.createFile(path);
        }

        Properties props = new Properties();
        try (InputStream is = Files.newInputStream(path.toFile().toPath())) {
            props.load(is);
        }

        String secret = props.getProperty(JWT_SECRET_KEY);

        if (secret == null || secret.trim().isEmpty()) {
            // 生成 HS512 密钥
            // 使用 JJWT 生成符合 HS512 标准的密钥
            SecretKey key = Jwts.SIG.HS512.key().build();

            // 输出 Base64 编码格式（推荐用于 application.yml）
            String base64Secret = Base64.getEncoder().encodeToString(key.getEncoded());
            System.out.println("🔐 Secret Key (Base64): " + base64Secret);
            // 写入配置文件
            props.setProperty(JWT_SECRET_KEY, base64Secret);
            try (OutputStream os = Files.newOutputStream(path.toFile().toPath())) {
                props.store(os, "Auto-generated JWT Secret for HS512");
            }
            System.out.println("JWT Secret generated and saved to config/local-config.properties");
        } else {
            System.out.println("🔐 Using existing JWT Secret from config/local-config.properties");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("spring.config.additional-location", "file:./config/");
        application.setDefaultProperties(map);
        return application;
    }
}